package com.dfrz.problem.dao.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dfrz.problem.dao.ProjectDao;
import com.dfrz.problem.model.ProjectInfo;

public class ProjectDaoImpl implements ProjectDao {
	public static final Logger logger = LoggerFactory.getLogger(ProjectDaoImpl.class);
	public SessionFactory sessionFactory;
	
	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	@Override
	public boolean addProjectInfo(ProjectInfo projectInfo) {
		getSession().save(projectInfo);
		logger.debug("新增项目"+projectInfo.getProjectId());
		return true;
	}
	
	@Override
	public ProjectInfo getProjectInfo(Integer projectId) {
		String sql = "from ProjectInfo where project_id=:projectId";
		Query query = getSession().createQuery(sql);
		query.setParameter("projectId", projectId);
		return (ProjectInfo) query.uniqueResult();
	}
	
	@Override
	public List<ProjectInfo> getAllProjectInfos() {
		String hql = "FROM ProjectInfo";
		Query query = getSession().createQuery(hql);
		@SuppressWarnings("unchecked")
		List<ProjectInfo> list = query.list();
		return list;
	}
	
	@Override
	public List<ProjectInfo> getProjectInfos(Integer pmId) {
		String hql = "FROM ProjectInfo where pm_id=:pmId";
		Query query = getSession().createQuery(hql);
		query.setParameter("pmId", pmId);
		@SuppressWarnings("unchecked")
		List<ProjectInfo> list = query.list();
		return list;
	}
	
	@Override
	public void updateProject(ProjectInfo projectInfo) {
		getSession().update(projectInfo);
	}
	
	@Override
	public void deleteProject(ProjectInfo projectInfo) {
		getSession().delete(projectInfo);
	}

	@Override
	public void createProject(){
		if(getSession().createQuery("FROM ProjectInfo").list().size() == 0){
			getSession().save(new ProjectInfo(1, 0, 1, "空白项目", "空白项目", new Date(), 30));
			logger.debug("创建默认的系统角色...");
		}
	}
}